import { Injectable } from '@angular/core';
import { Http }    from '@angular/http';
import 'rxjs/add/operator/toPromise';

 
@Injectable()
export class AuthService {
  currentUser: any;
  constructor(private http: Http) { }

  public login(credentials) {
    let self = this
    return this.http.post('/api/user/login', credentials)
      .toPromise()
      .then(response => {
        self.currentUser =  response.json()
        return self.currentUser
      })
  }
 
  public register(user) {
    return this.http.post('/api/user/register', user)
      .toPromise()
      .then(response => {
        return response.json()
      })
  }
  public modifyUser(user) {
    return this.http.post('/api/user/modify', user)
      .toPromise()
      .then(response => {
        return response.json()
      })
  }
  public getUserInfo()  {
    if (!this.currentUser && localStorage.factory) {
      this.currentUser = {
        factory: JSON.parse(localStorage.factory),
        user: JSON.parse(localStorage.user)
      }
    }
    return this.currentUser;
  }
  
  public logout() {
    localStorage.removeItem('user')
    localStorage.removeItem('factory')
    window.location.reload()
  }

}
